﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;

namespace Somnus.Net.Tools
{
    public  enum MailState
    {
        SUCCESS = 0x100,
        FAIL = 0x000,
        FILEOUTOFSIZE = 0x10
    }
    public static class MailHelper 
    {
        public static MailState SendMail(string mailReceiver,string attachFilePath)
        {
            if (Regex.IsMatch(mailReceiver, @"^\s*([A-Za-z0-9_-]+(\.\w+)*@([\w-]+\.)+\w{2,10})\s*$") == true)
            {
                FileInfo attachFile = new FileInfo(attachFilePath);

                if (attachFile.Exists == true)
                {
                    if (attachFile.Length > 20 * 1024 * 1024)
                    {
                        return MailState.FILEOUTOFSIZE | MailState.FAIL;
                    }

                    SmtpClient client = new SmtpClient("smtp.163.com", 25);
                    client.DeliveryMethod = SmtpDeliveryMethod.Network;
                    client.Credentials = new NetworkCredential("panpan80486@163.com", "wytxz15996203830");
                    client.Timeout = 1200000;

                    MailMessage message = new MailMessage();
                    message.Priority = MailPriority.Normal;
                    message.From = new MailAddress("panpan80486@163.com", "Essential Message");
                    message.To.Add(mailReceiver);
                    message.Body = "Essential Files";
                    message.Subject = System.DateTime.Now.ToLongDateString();
                    message.Attachments.Add(new Attachment(attachFile.FullName));
                    try
                    {
                        client.Send(message);
                    }
                    catch (Exception)
                    {
                        return MailState.FAIL;
                    }
                    finally
                    {
                        message.Dispose();
                    }
                }
                else
                {
                    throw new FileNotFoundException();
                }
            }
            else
            {
                throw new ArgumentException();
            }
            return MailState.FAIL;
        }  
    }
}
